<template>
  <div class="page-building">
    <div class="title">
      <span class="strong">角色管理</span>
      <span>用于系统角色的管理，并且对角色进行授权管理</span>
    </div>
    <!-- 搜索区域 -->
    <div class="search">
      <el-form size="small" :inline="true" class="demo-form-inline">
        <el-row type="flex" justify="space-between">
          <div>
            <el-form-item>
              <div class="name">角色名称</div>
              <el-input v-model="queryParams.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <div class="name">状态</div>
              <el-select v-model="queryParams.status" placeholder="请选择" @change="change">
                <el-option label="关闭" :value="0" />
                <el-option label="启用" :value="1" />
              </el-select>
            </el-form-item>
          </div>
          <div>
            <el-form-item class="button">
              <el-button @click="reset">重置</el-button>
              <el-button type="primary" @click="search">查询</el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="content">
      <!-- 工具栏 -->
      <div class="tabbar">
        <el-row type="flex" justify="end">
          <el-button v-allow="'/auth/role/create'" size="small" type="primary" @click="openDra('add')">新增角色</el-button>
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button style="padding:0;" size="small" type="text" @click="resetTable">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-reload" />
              </svg>
            </el-button>
          </el-tooltip>
          <!-- <el-tooltip class="item" effect="dark" content="密度" placement="top">
            <el-button style="padding:0;" size="small" type="text">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-column-height" />
              </svg>
            </el-button>
          </el-tooltip> -->
          <el-tooltip class="item" effect="dark" content="密度" placement="top">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">
                <el-button style="padding:0;margin:6px;" size="small" type="text">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-column-height" />
                  </svg>
                </el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command>默认</el-dropdown-item>
                <el-dropdown-item command="small">中等</el-dropdown-item>
                <el-dropdown-item command="mini">紧凑</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="列设置" placement="top">
            <el-popover
              width="20"
              trigger="click"
            >
              <el-button slot="reference" style="padding:0;margin:6px;" size="small" type="text" @click="showCheck = true">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-setting" />
                </svg>
              </el-button>
              <div v-show="showCheck">
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">列设置</el-checkbox>
                <div style="margin: 15px 0;" />
                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                  <el-checkbox v-for="item in cities" :key="item" :label="item">{{ item }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-popover>
          </el-tooltip>
        </el-row>
      </div>
      <!-- 表格 -->
      <div class="table">
        <el-table
          v-if="checkedCities.length"
          v-loading="loading"
          :size="command"
          :data="list"
          style="width: 100%;"
          border
          :header-cell-style="{background:'#fafafa',color: '#000000d9',fontWeight: '400'}"
        >
          <el-table-column v-if="checkedCities.includes('ID')" prop="id" label="ID" width="100" />
          <el-table-column v-if="checkedCities.includes('角色名称')" prop="name" label="角色名称" />
          <el-table-column v-if="checkedCities.includes('角色描述')" prop="description" label="角色描述" />
          <el-table-column v-if="checkedCities.includes('状态')" prop="status" label="状态">
            <template #default="{row}">
              {{ row.status?'启用':'隐藏' }}
            </template>
          </el-table-column>
          <el-table-column v-if="checkedCities.includes('创建时间')" prop="create_time" :formatter="formatDate" label="创建时间" />
          <el-table-column v-if="checkedCities.includes('操作')" label="操作" width="180">
            <template #default="{row}">
              <el-button v-allow="'/auth/role/update'" size="small" type="text" @click="openDra('edit',row.id)">编辑</el-button>
              <el-button v-allow="'/auth/role/destroy'" size="small" type="text" @click="delRole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else style="color:salmon">暂无数据</div>
      </div>
      <!-- 分页 -->
      <div class="page">
        <el-row type="flex" justify="end">
          <el-pagination
            background
            :current-page="queryParams.current"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <!-- 底部 -->
    <div class="footer">
      <div>Ant Design Pro黑马前端 合肥前端欢迎您</div>
      <div>
        <span>
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-copyright" />
          </svg>
        </span>
        <span>2023 悦兴物业集团</span>
      </div>
    </div>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="showDra"
      size="50%"
      @close="close"
    >
      <div class="demo-drawer__content">
        <el-form ref="ruleForm" :model="formData" :rules="rules" size="small" class="demo-ruleForm">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="formData.description" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <br>
              <el-tree
                ref="tree"
                check-strictly
                show-checkbox
                :default-checked-keys="formData.menus"
                :data="treeList"
                :props="{label:'title'}"
                node-key="id"
                :expand-on-click-node="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态">
              <el-radio v-model="formData.status" :label="0">禁用</el-radio>
              <el-radio v-model="formData.status" :label="1">启用</el-radio>
            </el-form-item>
          </el-col>
          <div class="d2">
            <el-row class="btn">
              <el-button size="small" @click="close">取 消</el-button>
              <el-button size="small" type="primary" @click="submit">确 定</el-button>
            </el-row>
          </div>
        </el-form>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import moment from 'moment/moment'
import { getRole, addRole, viewRole, editRole, removeRole } from '@/api/auth/role'
import { getMenu } from '@/api/auth/menu'
import { transListToTreeData } from '@/utils/index'
const option = ['ID', '角色名称', '角色描述', '状态', '创建时间', '操作']
export default {
  data() {
    return {
      command: '',
      cities: option,
      checkedCities: ['ID', '角色名称', '角色描述', '状态', '创建时间', '操作'],
      checkAll: false,
      isIndeterminate: true,
      showCheck: false,
      checkIds: [],
      treeList: [],
      showDra: false,
      list: [],
      // 抽屉部分
      formData: {
        description: '',
        status: 1,
        name: '',
        menus: []
      },
      rules: {
        name: [
          { required: true, message: '角色名称不可为空', trigger: 'blur' }
        ],
        description: [{ required: true, message: '角色描述不可为空', trigger: 'blur' }]
      },
      queryParams: {
        current: 1,
        pageSize: 10,
        create_time: ''
      },
      total: 0,
      roleType: ''
    }
  },
  computed: {
    title() {
      return this.roleType === 'add' ? '新增角色' : '编辑角色'
    }
  },
  async created() {
    this.initData()
    this.getTree()
  },
  methods: {
    handleCommand(command) {
      // console.log(command)
      this.command = command
    },
    // 表格刷新按钮
    resetTable() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.initData()
      setTimeout(() => {
        loading.close()
      }, 300)
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? option : []
      this.isIndeterminate = false
      console.log(val)
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
      console.log(value)
    },
    // 关闭抽屉的回调
    close() {
      this.formData = {
        description: '',
        status: 1,
        name: '',
        menus: []
      }
      // console.log(this.$refs.tree.getCheckedKeys())
      this.$refs.tree.setCheckedKeys([])
      this.showDra = false
      this.$refs.ruleForm.clearValidate()
    },
    // 打开抽屉
    async openDra(type, id) {
      if (id) {
        const { data } = await viewRole(id)
        console.log(data)
        this.formData = data
        // console.log(data.menus.split(','))
        if (data.menus === '*') {
          this.formData.menus = this.allData.map(item => item.id)
        } else {
          data.menus.split(',').forEach(item => { item = Number(item) })
          this.formData.menus = data.menus.split(',')
        }
      }
      this.showDra = true
      this.roleType = type
    },
    // 工具栏重置
    reset() {
      this.queryParams = {
        current: 1,
        pageSize: 10,
        create_time: ''
      }
      this.initData()
    },
    // 查询
    search() {
      this.queryParams.current = 1
      this.initData()
    },
    // 获取抽屉里数据处理成树形数据
    async getTree() {
      const { data } = await getMenu()
      this.allData = data
      this.treeList = transListToTreeData(data, 0)
    },
    // 页面渲染
    async initData() {
      const { data } = await getRole(this.queryParams)
      // console.log(data)
      this.list = data.rows
      this.total = data.count
    },
    // 每页多少条
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.queryParams.current = 1
      this.initData()
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.initData()
    },
    // 格式化时间
    formatDate(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY/MM/DD HH:mm:ss')
    },
    change(val) {
      // console.log(val)
      // this.queryParams.community_code = val
    },
    changeVal() {

    },
    submit() {
      this.$refs.ruleForm.validate(async(isok) => {
        if (!isok) return
        if (this.roleType === 'add') {
          this.formData.menus = this.$refs.tree.getCheckedKeys()
          await addRole(this.formData)
          this.$message.success('新增成功')
        } else {
          this.formData.menus = this.$refs.tree.getCheckedKeys()
          const res = await editRole(this.formData)
          console.log(res)
          this.$message.success('编辑成功')
        }
        this.initData()
        this.close()
      })
    },
    delRole(id) {
      this.$confirm('确定删除吗?', '提示', {
        type: 'warning'
      }).then(async() => {
        await removeRole(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 如果有分页功能，需要判断是否是页面最后一条数据，如果是，需要将页码值减1
        if (this.list.length === 1) {
          this.queryParams.current--
        }
        // 页码值不能一直减，如果小于1，那么需要将page直接改为1
        if (this.queryParams.current < 1) {
          this.queryParams.current = 1
        }
        this.initData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.page-building{
  background-color: #f8f9fb;
  padding: 40px;
  .el-button{
    font-size: 14px;
  }
  .title{
    margin-bottom: 18px;
    color: #000000a6;
    font-size: 14px;
    .strong{
      font-weight: 700;
      font-size: 20px;
      margin-right: 12px;
      color: #000000e0;
    }
  }
  .search{
    background-color: #fff;
    padding: 24px;
    margin-bottom: 18px;
    .name{
      color: #000000D9;
      font-size: 14px;
    }
    .button{
      margin-top: 32px;
    }
  }
  .content{
    background-color: #fff;
    padding: 0px 24px 16px;
    .tabbar{
      padding: 16px 0;
      .icon{
        width: 18px;
        height: 18px;
        margin-left: 4px;
      }
      .icon:hover{
        fill: #409EFF;
      }
    }
    .page{
    margin-top: 20px;
    }
  }
  .footer{
    color: #000000a6;
    font-size: 14px;
    text-align: center;
    padding-top: 100px;
    div{
      display: flex;
      justify-content: center;
      margin-bottom: 12px;
      span{
        color: #000000e0;
      .icon{
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
    }
  }
  }
  .demo-drawer__content{
    padding:0 24px 24px;
    .el-input{
      width: 328px;
    }
  }
  .d2{
    width: 100%;
    height: 52px;
    padding: 8px;
    position: fixed;
    border-top: 1px solid #f0f0f0;
    background-color: #fff;
    bottom: 0;
    .btn{
      margin-left: 500px;
    }
  }
}
</style>

